from fastapi import APIRouter, Depends, HTTPException
from fastapi.security import OAuth2PasswordRequestForm
from sqlalchemy.orm import Session
from . import baseModel, crud, dependencies
from .database import SessionLocal


def get_db():
    """
    创建数据库会话
    :return: 数据库会话
    """
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close()


router = APIRouter(
    prefix="/user",
    tags=["items"],
    responses={404: {"description": "Not found"}},
)


@router.post("/login", response_model=baseModel.UserAndToken)
async def login(form_data: OAuth2PasswordRequestForm = Depends(), db: Session = Depends(get_db)):
    """
    登录接口
    :param form_data: 登录所需信息
    :param db: 数据库会话
    :return: 用户信息与token
    """
    user = dependencies.authenticate_user(db, form_data.username, form_data.password)
    if not user:
        raise HTTPException(status_code=400, detail={
            "info": "账号或密码错误",
            "tip": "请检查账号或者密码"
        })
    token = dependencies.create_access_token(data={
        "sub": user.account
    })

    return {
        "userInfo": user,
        "token": token,
    }


@router.get("/token", response_model=baseModel.User)
async def token(account: str = Depends(dependencies.token_analysis), db: Session = Depends(get_db)):
    """
    查证token
    :param account: 账号
    :param db: 数据库会话
    :return: 用户信息
    """
    user_db = crud.get_user_by_account(db, account)
    if not user_db:
        raise HTTPException(status_code=400, detail={
            "info": "查无此人"
        })
    return user_db


@router.post("/create", response_model=baseModel.User)
async def create(user_create: baseModel.UserCreate, db: Session = Depends(get_db)):
    """
    创建用户
    :param user_create: 创建用户的baseModel  请求体
    :param db: 数据库会话
    :return: 新用户信息
    """
    db_user = crud.get_user_by_account(db=db, account=user_create.account)
    if db_user:
        raise HTTPException(status_code=400, detail={
            "info": "账号已存在"
        })
    new_user = crud.create_user(db=db, user_create=user_create)
    if not new_user:
        raise HTTPException(status_code=400, detail={
            "info": "账号密码长度应大于等于六位数"
        })
    return new_user


@router.post("/super_create", response_model=baseModel.User)
async def super_create(
        user_create: baseModel.SuperUserCreate,
        db: Session = Depends(get_db),
        super_account: str = Depends(dependencies.token_analysis)
):
    """
    创建高级用户
    :param super_account:
    :param user_create: 创建用户的baseModel  请求体
    :param db: 数据库会话
    :return: 新用户信息
    """
    super_user = crud.get_user_by_account(db, super_account)
    # 被创建用户权限必须小于自身权限
    if not user_create.power.value < super_user.power.value:
        raise HTTPException(status_code=400, detail={
            "info": "权限不足"
        })

    db_user = crud.get_user_by_account(db=db, account=user_create.account)
    if db_user:
        raise HTTPException(status_code=400, detail={
            "info": "账号已存在"
        })
    print(user_create.power)
    print(user_create.power.value)
    new_user = crud.create_user(db=db, user_create=user_create, power=user_create.power)
    if not new_user:
        raise HTTPException(status_code=400, detail={
            "info": "账号密码长度应大于等于六位数"
        })
    return new_user
